<template>
    <div>
      <q-list bordered class="rounded-borders  no-shadow">
        <q-expansion-item
          @show="show"
          ref="item"
          @before-show="prevent"
          header-class="bg-grey-2"
          switch-toggle-side
          expand-separator
          label="品类"
        >
          <q-separator />
          <template v-slot:header style="max-height:35px;">
            <div align="right" style="padding-top:5px;">品类</div>
            <div  style="position: absolute;right:0;top:3px;z-index:86;margin-right:30px;">
            <q-btn size="sm" outline color="nlack" :label="$t('保存')" @click.stop="add"/>
            <!-- <q-btn size="sm" outline color="nlack" :label="$t('编辑')" @click.stop="modify"  v-if="ischeck==2"/> -->
            </div>
          </template>
            <div class="row gutter-lg" style="height:100%;">
              <div class="col-12" style="min-height:220px;border-right:1px solid #ccc;">
                <q-tabs
                  v-model="caTab"
                  dense
                  inline-label
                  class="text-grey"
                  active-color="primary"
                  indicator-color="primary"
                  align="left"
                  :breakpoint="0"
                  narrow-indicator
                >
                  <q-tab name="tab1"  label="待选品类" />
                  <q-tab name="tab2"  label="已选品类" />
                </q-tabs>
                <q-separator />
                <q-tab-panels v-model="caTab" animated>
                  <q-tab-panel class="q-pa-none" name="tab1">
                    <q-splitter
                      v-model="splitterModel"
                      style="width:100%"
                    >
                      <template v-slot:before style="width:10%;">
                        <q-tabs
                          v-for="(data,index) in classificationdata"
                          :key="index"
                          v-model="tab"
                          vertical
                          dense
                          align="left"
                          class="text-teal"
                        >
                          <q-tab  :name="data.id" :label="data.name" />
                        </q-tabs>
                      </template>
                      <template v-slot:after>
                        <q-tree
                          style="margin:10px 0 10px 40px;"
                          :filter="filter"
                          :nodes="data"
                          no-nodes-label="找不到匹配数据!"
                          node-key="id"
                          color="primary"
                          label-key="name"
                          selected-color="primary"
                          :selected.sync="selected"
                          :ticked.sync="ticked"
                          :tick-strategy="tickStrategy"
                          ref="trees"
                          @update:ticked="tickeds"
                          :expanded.sync="nodeExpand">
                        </q-tree>
                        <!-- <el-tree
                          :data="data"
                          show-checkbox
                          node-key="id"
                          :props="defaultProps"
                          ref="tree"
                          check-strictly
                          :current-node-key="selected"
                          @current-change="handleNodeClick"
                          @check-change="handleCheckChange"
                          :default-checked-keys="ticked"></el-tree> -->
                      </template>
                    </q-splitter>
                  </q-tab-panel>
                  <q-tab-panel class="q-pa-none" name="tab2">
                    <q-table
                      flat
                      dense
                      class="bg-white"
                      :data="dataDep"
                      :columns="columnsDep"
                      row-key="id"
                      separator="cell"
                      selection="multiple"
                      :selected.sync="selectedDep"
                      :visible-columns="visibleColumnsDep"
                      :pagination.sync="paginationDep"
                      :rows-per-page-options="[10, 20, 30, 40]"
                      :filter="searchFormDep"
                      no-data-label="暂无数据"
                      table-class="h-custom"
                      @request="getSeleetTable"
                    >
                      <template v-slot:top-right="props">
                        <q-select
                          v-model="visibleColumnsDep"
                          multiple
                          borderless
                          options-dense
                          :display-value="$t('显示列')"
                          emit-value
                          map-options
                          :options="columnsDep"
                          option-value="name"
                          class="q-mx-lg"
                        >
                          <template v-slot:option="scope">
                            <q-item
                              v-bind="scope.itemProps"
                              v-on="scope.itemEvents"
                              v-if="!scope.opt.required"
                            >
                              <q-item-section avatar>
                                <q-toggle color="blue" v-model="visibleColumnsDep" :val="scope.opt.name" />
                              </q-item-section>
                              <q-item-section style="min-width:60px">
                                {{ scope.opt.label }}
                              </q-item-section>
                            </q-item>
                          </template>
                        </q-select>
                        <q-toggle
                          v-model="searchToggleDep"
                          left-label
                          label="搜索"
                          color="blue"
                          checked-icon="check"
                          unchecked-icon="clear"
                          keep-color
                        />
                        <q-btn
                          flat round dense
                          :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'"
                          @click="props.toggleFullscreen"
                          class="q-ml-md"
                        />
                      </template>
                      <template v-if="searchToggleDep" v-slot:top-row="props">
                        <q-tr :props="props">
                          <q-td>
                            <q-btn color="primary" dense flat icon="search" @click="listGet({ pagination: pagination, filter: searchFormDep })"/>
                          </q-td>
                          <q-td v-for="col in props.cols" :key="col.name" class="relative-position">
                            <!-- <q-btn color="primary" dense flat icon="search" class="absolute-center" v-if="col.name==='action'" @click="listGet({ pagination: pagination, filter: searchFormGroup })"/> -->
                            <q-input dense outlined v-model="searchFormDep[col.name]"/>
                          </q-td>
                        </q-tr>
                      </template>
                      <template v-slot:header="props">
                        <q-tr :props="props">
                          <q-th>
                            <q-checkbox indeterminate-value="some" dense v-model="props.selected" />
                          </q-th>
                          <q-th v-for="col in props.cols" :key="col.name" :props="props">
                            {{ col.label }}
                          </q-th>
                        </q-tr>
                      </template>
                      <template v-slot:body="props">
                        <q-tr :props="props">
                          <q-td width="52">
                            <q-checkbox dense v-model="props.selected" />
                          </q-td>
                          <q-td key="action" :props="props">
                            <q-btn-dropdown
                              color="blue"
                              size="sm"
                              dense
                              menu-anchor="bottom left"
                              menu-self="top left"
                              content-class="text-grey"
                              icon="settings">
                              <q-list dense>
                                <q-item clickable v-close-popup @click="delGroupRowDep(props.row)">
                                  <q-item-section>
                                    <q-item-label>删除</q-item-label>
                                  </q-item-section>
                                </q-item>
                              </q-list>
                            </q-btn-dropdown>
                          </q-td>
                          <q-td key="categoryCode" :props="props">{{ props.row.categoryCode  }}</q-td>
                          <q-td key="categoryName" :props="props">{{ props.row.categoryName }}</q-td>
                          <q-td key="categoryTypeCode" :props="props">{{ props.row.categoryTypeCode }}</q-td>
                          <q-td key="categoryTypeName" :props="props">{{ props.row.categoryTypeName }}</q-td>
                          <q-td key="createUserName" :props="props">{{ props.row.createUserName }}</q-td>
                          <q-td key="createTime" :props="props">{{ props.row.createTime }}</q-td>
                        </q-tr>
                        <q-tr v-show="props.expand" :props="props">
                          <q-td colspan="100%">
                          </q-td>
                        </q-tr>
                      </template>
                      <template v-slot:pagination="props">
                        <q-pagination
                          v-model="paginationDep.page"
                          color="blue"
                          :max-pages="5"
                          :max="1"
                          :boundaryLinks="true"
                          :directionLinks="true"
                        />
                        <!-- 共 {{ totalDep }} 条 -->
                      </template>
                    </q-table>
                  </q-tab-panel>
                </q-tab-panels>
              </div>
            </div>
          <!-- <div style="width:400px;">
            <el-input v-model="filter" style="width:200px;margin:10px 0px 10px 40px;" placeholder="请输入品类名称"></el-input>
          </div> -->
          <!-- <q-tree
          style="margin:10px 0 10px 40px;"
          :filter="filter"
          :nodes="data"
          node-key="id"
          color="primary"
          label-key="name"
          selected-color="primary"
          :selected.sync="selected"
          :ticked.sync="ticked"
          :tick-strategy="tickStrategy"
          ref="trees"
          @update:ticked="tickeds"
          :expanded.sync="nodeExpand"> -->
          <!-- <el-tree
          :data="data"
          show-checkbox
          node-key="id"
          :props="defaultProps"
          ref="tree"
          :current-node-key="selected"
          @check-change="handleCheckChange"
          @current-change="change"
          :default-checked-keys="ticked">
        </el-tree> -->
          <!-- </q-tree> -->
        </q-expansion-item>
        <q-separator />
      </q-list>
    </div>
</template>

<script>
// import _ from 'lodash'
import { required } from 'vuelidate/lib/validators'
import { transformToTreeFormat } from 'src/utils/fns'
export default {
  name: 'leftNavs',
  props: {
    selectSiteId: {
    }
  },
  data () {
    return {
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      classificationdata: [],
      splitterModel: 20,
      tab: '',
      // 品类tab
      caTab: 'tab1',
      filter: '',
      data: [],
      ticked: [],
      tickStrategy: 'strict',
      selected: '',
      nodeExpand: [],
      nodeSelected: '',
      addOrEdit: 1,
      parentId: '0',
      maximizedToggle: false,
      loadingSave: false,
      addOrEditDialog: false,
      visibleColumnsDep: [
        'categoryCode',
        'categoryName',
        'categoryTypeCode',
        'categoryTypeName',
        'createUserName',
        'createTime'
      ],
      paginationDep: {
        page: 1,
        rowsPerPage: 10,
        rowsNumber: 10,
        sortBy: '',
        descending: Boolean
      },
      selectedDep: [],
      dataDep: [],
      datas: [],
      classification: {},
      searchToggleDep: false,
      // tickable: true,
      searchFormDep: {
        categoryCode: '',
        categoryName: '',
        categoryTypeCode: '',
        categoryTypeName: '',
        createUserName: '',
        createTime: ''
      },
      columnsDep: [
        { name: 'categoryCode', required: true, label: '品类编码', align: 'left', field: 'categoryCode', sortable: true },
        { name: 'categoryName', required: true, label: '品类名称', align: 'left', field: 'categoryName', sortable: true },
        { name: 'categoryTypeCode', required: true, label: '品类分类编码', align: 'left', field: 'categoryTypeCode', sortable: true },
        { name: 'categoryTypeName', required: true, label: '品类分类名称', align: 'left', field: 'categoryTypeName', sortable: true },
        { name: 'createUserName', field: 'createUserName', align: 'left', label: '创建人', sortable: true },
        { name: 'createTime', field: 'createTime', align: 'left', label: '创建时间', sortable: true }
      ]
    }
  },
  validations: {
    addOrEditForm: {
      name: { required },
      increase: { required },
      sn: { required }
    }
  },
  created () {
    // this.handleCheckChange()
    // this.ticked = ['c92c1db151af4aff81976229d13afc13', '02e1614f7f6541c78c34a38979ad28e8', 'da2511796a2846e2b8470f92665fcbf5', 'd9e45dabe45b4d6bb0bcaab04dfda193', '444a72949d0143e0871a19b470ac1962', '2c07dbf3dcba4c36b793b6df4f082a31']
  },
  watch: {
    'ticked' () {
    },
    'selectSiteId' () {
      this.getleft()
    },
    'tab' () {
      this.getTree()
      if (JSON.stringify(this.classification) === '{}') {
      } else {
        if (this.datas.length === 0) {
          if (this.classification.length !== 0) {
            this.datas.push(this.classification)
          }
        } else {
          this.getNew(this.datas)
        }
      }
      if (this.datas.length !== 0) {
        for (let i in this.datas) {
          if (this.datas[i].categroyTypeId === this.tab) {
            this.ticked = this.datas[i].categoryIds
            console.log(this.ticked)
          }
        }
      }
      this.classification = {}
    }
  },
  methods: {
    prevent (event) {
      if (this.selectSiteId.length === 0) {
        // console.log(this.$refs.item.hide(event))
        event.preventDefault()
      }
    },
    modify () {
      // this.tickable = true
      // this.ischeck = 1
      this.getTree()
    },
    // handleNodeClick (data, node, vuecomponent) {
    //   console.log('data:', data, '\n', 'node: ', node, '\n', 'vuecomponent', vuecomponent)
    // },
    show () {
      this.getleft()
      this.getSeleetTable()
      // this.$refs.trees.setTicked(['2c07dbf3dcba4c36b793b6df4f082a31'], true)
    },
    async getSeleetTable () {
      // let { sortBy, descending } = props.pagination
      await this.$api({
        method: 'get',
        url: `/mdm/item/category/findByItemSite/${this.selectSiteId}`,
        emulateJSON: true,
        useLoadLayer: true,
        // params: {
        //   sort: sortBy,
        //   order: descending === true ? 'desc' : (descending === false ? 'asc' : '')
        // },
        successCallback: ({ data }) => {
          if (data.length === 0) {
            this.dataDep = []
            this.tab = ''
          } else {
            this.dataDep = data
            this.datas = []
            // this.tickStrategy = 'leaf'
            // this.ischeck = 2
            data.forEach(item => {
              // this.tickable = false
              this.getleft()
              let cate = {}
              cate.categroyTypeId = item.categoryTypeId
              cate.categoryIds = [item.categoryId]
              this.datas.push(cate)
            })
            if (this.datas.length !== 0) {
              for (let i in this.datas) {
                if (this.datas[i].categroyTypeId === this.tab) {
                  this.ticked = this.datas[i].categoryIds
                }
              }
            }
            this.getTree()
          }
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    async add () {
      if (this.datas.length === 0 && this.ticked.length === 0) {
        this.$q.notify({
          message: '请选择品类',
          color: 'negative',
          icon: 'error_outline',
          position: 'top-right',
          timeout: 3000
        })
      } else {
        console.log(this.classification)
        this.classification = {}
        this.classification.categroyTypeId = this.tab
        this.classification.categoryIds = this.ticked
        if (JSON.stringify(this.classification) === '{}') {
        } else {
          if (this.datas.length === 0) {
            console.log(this.classification)
            if (this.classification.length !== 0) {
              this.datas.push(this.classification)
            }
          } else {
            this.getNew(this.datas)
          }
        }
        if (this.datas.length === 0) {
          this.$q.notify({
            message: '请选择品类',
            color: 'negative',
            icon: 'error_outline',
            position: 'top-right',
            timeout: 3000
          })
        } else {
          console.log(this.datas)
          await this.$api({
            method: 'put',
            url: `/mdm/item/category/save`,
            params: {
              categoryTypeCateRels: this.datas,
              itemSiteId: this.selectSiteId
            },
            emulateJSON: true,
            useLoadLayer: true,
            successCallback: ({ data }) => {
              // this.tickStrategy = 'leaf'
              // this.tickable = false
              // this.ischeck = 2
              this.getTree()
              this.getSeleetTable()
            },
            errorCallback (err) {
              console.log('未处理的业务级error：', err)
            }
          })
        }
      }
    },
    getNew (arr) {
      for (let i in arr) {
        if (arr[i].categroyTypeId === this.classification.categroyTypeId) {
          arr[i] = {}
          if (this.classification.categoryIds.length === 0) {
            arr.splice(i, 1)
          } else {
            arr[i] = this.classification
          }
          return arr
        }
      }
      arr.push(this.classification)
      for (let i in arr) {
        if (arr[i].categroyTypeId.length === 0) {
          this.splice(i, 1)
        }
      }
      console.log(arr)
    },
    handleCheckChange (data, checked) {
      if (checked) {
        let arr = [data.id]
        this.$refs.tree.setCheckedKeys(arr)
        console.log(this.$refs.tree.getHalfCheckedNodes())
      }
      // this.selected = data.id
      console.log(data)
    },
    // 单选
    tickeds (ticked, aaa) {
      if (ticked.length > 1) {
        this.tickStrategy = 'strict'
        this.ticked = [ticked[1]]
        this.classification = {}
        this.classification.categroyTypeId = this.tab
        this.classification.categoryIds = this.ticked
        console.log(this.classification)
      } else {
        this.classification = {}
        this.classification.categroyTypeId = this.tab
        this.classification.categoryIds = this.ticked
      }
    },
    async getleft () {
      if (this.selectSiteId.length === 0) {
        this.data = []
        this.$q.notify({
          message: '请先选择维护地点',
          color: 'negative',
          icon: 'error_outline',
          position: 'top-right',
          timeout: 3000
        })
      } else {
        await this.$api({
          method: 'post',
          url: `/mdm/categoryType/selectByItemSiteId/${this.selectSiteId}`,
          emulateJSON: true,
          useLoadLayer: true,
          successCallback: ({ data }) => {
            console.log(data)
            this.tab = 0
            this.classificationdata = data
            this.tab = data[0].id
            console.log(this.tab)
            this.getTree()
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
      }
    },
    tableDataGetDep () {
    },
    async getTree () {
      console.log(this.tab)
      if (this.selectSiteId.length === 0) {
        this.data = []
        this.$q.notify({
          message: '请先选择维护地点',
          color: 'negative',
          icon: 'error_outline',
          position: 'top-right',
          timeout: 3000
        })
      } else {
        this.data = []
        if (this.tab === '') {
          this.tab = 0
        }
        console.log(this.tab)
        await this.$api({
          method: 'post',
          url: `/mdm/category/query`,
          params: {
            categoryTypeId: this.tab
          },
          emulateJSON: true,
          useLoadLayer: true,
          successCallback: ({ data }) => {
            // console.log(data)
            let datas = data
            datas.forEach(item => {
              this.nodeExpand.push(item.id)
              // item.tickable = this.tickable
              item.name = String(item.code) + '-' + String(item.name)
            })
            let nodesCat = transformToTreeFormat(datas, 'id', 'parentId', 'children')
            console.log(nodesCat)
            this.data = nodesCat
            // this.ticked = ['b40415da202c4077bbdde37e8495df7b']
            console.log(this.ticked)
            // this.selected = this.nodes[0].id
            // console.log(this.data)
            // console.log(this.nodes)
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
  /deep/.q-item
    min-height 30px
    max-height 35px
  /deep/ .q-splitter__before
    width 20% !important
    margin-left 20px
    min-height 200px
  /deep/ .q-splitter__after
    width 80% !important
  /deep/ .text-center
    text-align left !important
  .q-checkbox__check-indet
    width: 100%;
    height: 0;
    left: 0;
    top: 50%;
    border-color: #fff;
    border-width: 1px;
    border-style: solid;
</style>
